//
//  NewNoteViewController.swift
//  todoApp
//
//  Created by lili on 15/2/4.
//  Copyright (c) 2015年 ll studio. All rights reserved.
//

import UIKit
import YYText

class NewNoteViewController: UIViewController, UINavigationControllerDelegate {

    private let noteFont = UIFont.systemFontOfSize(18)
	@IBOutlet weak var noteTagField: YQAutoCompleteTextField!
	@IBOutlet weak var noteContent: YYTextView!
    
	lazy var picker: UIImagePickerController = {
		let picker = UIImagePickerController()
		picker.delegate = self
		return picker
	}()

	override func viewDidLoad() {
		super.viewDidLoad()
        setupUI()
        registKeyboardHandler()
	}

    private func setupUI() {
        {
            noteContent.font = noteFont
            noteContent.placeholderFont = noteFont
            noteContent.placeholderText = "请输入备忘录文字"
        }()
        
        view.backgroundColor = BACKGROUND_COLOR
        noteTagField.inputField.placeholder = "备忘录标签";
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), { _ in
            self.noteTagField.dataSourceArray = self.existTags()
        })
    }
    
    private func registKeyboardHandler() {
        YYTextKeyboardManager.defaultManager()?.addObserver(self)
    }
    
    private func unregistKeyboardHandler() {
        YYTextKeyboardManager.defaultManager()?.removeObserver(self)
    }
    
	@IBAction func backBtnClick(sender: AnyObject) {
		let str: NSString? = nil
		let tag: NSString? = self.noteTagField.text

		if str?.length != 0 || (tag?.length != 0 && tag != nil)
		{
			UIAlertView.showWithTitle("", message: "保存此条备忘录？", cancelButtonTitle: "保存", otherButtonTitles: ["不保存"]) { (alter, index) -> Void in
				if index == 1
				{
					self.navigationController?.popViewControllerAnimated(true)
				} else
				{
					self.donePressed(UIBarButtonItem())
				}
			}
		} else
		{
			self.navigationController?.popViewControllerAnimated(true)
		}
	}
    
	@IBAction func donePressed(sender: UIBarButtonItem) {
        guard noteContent.text.characters.count > 0 else {
            UIAlertView.showWithTitle("", message: "请输入备忘录文字", cancelButtonTitle: "确定", otherButtonTitles: nil, tapBlock: nil)
            return
        }
        
        let note = NoteModel()
        note.noteTag = noteTagField.text
        note.noteText = noteContent.text

		if let uid = userId()
		{
			note.userId = uid as String
		}

		// 使用创建备忘的时间戳来作为唯一标示
		let currentDate = NSDate()
		let dateFormatter = NSDateFormatter()
		dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"

		let dateString = dateFormatter.stringFromDate(currentDate)
		note.noteId = dateString

		NoteDBManger.shareInstance().addNotes([note])

		let newNoteObj = AVObject(className: "NoteClass")
		let arr : NSArray = NSArray(object: NSDictionary(objects: [newNoteObj, note], forKeys: ["avosObj", "noteObj"]))
		startUploadData(0, uploadArray: arr)
        
		navigationController?.popToRootViewControllerAnimated(true)
	}

	deinit {
        unregistKeyboardHandler()
	}
}

// MARK: - action methods
extension NewNoteViewController {
	@IBAction func cameraButtonPress(sender: UIBarButtonItem) {
        view.endEditing(true)
		if self.noteContent.textLayout?.attachments?.count == 5 {
			let alert = UIAlertView(title: "提示", message: "最多只能插入五张图片", delegate: nil, cancelButtonTitle: "确定")
			alert.show()
			return
		}
		let alert = UIAlertController(title: "选择照片", message: nil, preferredStyle: .ActionSheet)
		alert.addAction(UIAlertAction(title: "图库", style: .Default, handler: { [weak self](_) -> Void in
			self?.loadPhotos()
		}))
		alert.addAction(UIAlertAction(title: "相机", style: .Default, handler: { [weak self](_) -> Void in
			self?.openCamera()
		}))
		presentViewController(alert, animated: true, completion: nil)
	}
}

// MARK: - UIImagePickerControllerDelegate
extension NewNoteViewController: UIImagePickerControllerDelegate {
	func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {

        picker.dismissViewControllerAnimated(true, completion: {
            let width = self.noteContent.contentSize.width
            let scale = image.size.width / width
            let attr = { _ -> NSMutableAttributedString in
                if let attrText = self.noteContent.attributedText {
                    return attrText.mutableCopy() as! NSMutableAttributedString
                } else {
                    return NSMutableAttributedString()
                }
            }()
            let selectedImage = UIImage(CGImage: image.CGImage!, scale: scale, orientation: .Up)
            let selectedImageView = UIImageView(frame: CGRect(x: 0, y: 0, width: selectedImage.size.width, height: selectedImage.size.height))
            selectedImageView.image = selectedImage
            selectedImageView.userInteractionEnabled = true
            selectedImageView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: "tapImageViewHandler:"))
            let out = NSMutableAttributedString.yy_attachmentStringWithContent(selectedImageView, contentMode: .Center, attachmentSize: selectedImageView.frame.size, alignToFont: self.noteFont, alignment: .Center)
            attr.appendAttributedString(out)
            attr.yy_font = self.noteFont
            self.noteContent.attributedText = attr
        })
    }
    private func loadPhotos() {
        picker.sourceType = .PhotoLibrary
        presentViewController(picker, animated: true, completion: nil)
    }
    
    private func openCamera() {
        if (UIImagePickerController.availableCaptureModesForCameraDevice(.Rear) != nil) {
            picker.sourceType = .Camera
            presentViewController(picker, animated: true, completion: nil)
        } else {
            let alert = UIAlertView(title: "提示", message: "不能打开相机", delegate: nil, cancelButtonTitle: "确定")
            alert.show()
        }
    }
    
    dynamic private func tapImageViewHandler(sender: UITapGestureRecognizer) {
        guard let selectedImageView = sender.view as? UIImageView else { return }
        let alert = UIAlertController(title: "编辑图片", message: nil, preferredStyle: .ActionSheet)
        alert.addAction(UIAlertAction(title: "删除", style: .Destructive, handler: { (_) -> Void in
            var imageIndex: Int?
            self.noteContent.textLayout?.attachments?.enumerate().forEach({ (index: Int, element: YYTextAttachment) -> () in
                guard let content = element.content as? UIImageView else {
                    return
                }
                if content == selectedImageView {
                    imageIndex = index
                }
            })
            guard let index = imageIndex else {
                return
            }
            
            if let range = self.noteContent.textLayout?.attachmentRanges?[index] {
                guard let attr = self.noteContent.attributedText?.mutableCopy() as? NSMutableAttributedString else {
                    return
                }
                attr.deleteCharactersInRange(range.rangeValue)
                attr.yy_font = self.noteFont
                self.noteContent.attributedText = attr
                self.noteContent.selectedRange = NSMakeRange(0, 0)
            }
        }))
        
        alert.addAction(UIAlertAction(title: "编辑", style: .Default, handler: { _ in
        
        }))
        
        alert.addAction(UIAlertAction(title: "取消", style: .Default, handler: { _ in
        
        }))
        presentViewController(alert, animated: true, completion: nil)
    }
}

extension NewNoteViewController: YYTextKeyboardObserver {
    func keyboardChangedWithTransition(transition: YYTextKeyboardTransition) {
        
    }
}

